package com.example.blog.service;

import com.example.blog.mapper.BlogInfoMapper;
import com.example.blog.mapper.UserInfoMapper;
import com.example.blog.model.BlogInfo;
import com.example.blog.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserService {
    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    BlogInfoMapper blogInfoMapper;

    public UserInfo getUserByName(String username) {
        return userInfoMapper.selectByName(username);
    }

    public UserInfo selectById(Integer userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Integer count = blogInfoMapper.count(userInfo.getId());
        log.info("count: {}",count);
        userInfo.setCount(count);
        return userInfo;
    }

    public UserInfo getAuthorInfo(Integer blogId) {
        log.info("blogId: {}",blogId);
        BlogInfo blogInfo = blogInfoMapper.selectById(blogId);
        if (blogInfo == null || blogInfo.getUserId() <= 0) {
            log.error("图书不存在或图书作者信息不合法");
            return null;
        }
        UserInfo userInfo = userInfoMapper.selectById(blogInfo.getUserId());
        Integer count = blogInfoMapper.count(userInfo.getId());
        log.info("count: {}",count);
        userInfo.setCount(count);
        return userInfo;
    }

    public Integer insert(UserInfo userInfo) {
        try {
            int insert = userInfoMapper.insert(userInfo);
            return insert;
        } catch (Exception e) {
            log.error("插入失败");
            return -1;
        }
    }
}
